# -*- coding: utf-8 -*-
"""
@Time       :   2024/05/21
@Author     :   Li Kuangyuan, Yi Junquan
@Version    :   1.0
@Contact    :   1767958859@qq.com
@Software   :   VsCode
"""
import csv
import os
import pickle

from util.types import NRange, GTree


# 比较ab的大小, 返回对应数字(> 1, < -1, = 0)
def cmp_num(a, b):
    # 若是字符, 转为浮点
    if type(a) == str:
        a = float(a)
        b = float(b)
    if a > b:
        return 1
    if a < b:
        return -1
    return 0

def get_num_list_from_str(tmp_str):
    """
    将字符串转化为数字列表
    """
    try:    # 如果传入的字符串可以转化为float, 封装成列表返回
        float(tmp_str)
        return [tmp_str]
    except ValueError:  # 不能转化的情况, 一定是用‘,’分割的数字列表
        return tmp_str.split(',')


def read_tree_data(path, statistic_path, dataset, attribute_names, quasi_index_list, category_flag_list):
    """读取统计数据，以树的形式存储返回
        参数说明: 
            path, statistic_path: 数据存储路径(result/generalization and result/numeric)
            dataset: 数据集名称
            attribute_names: 数据集表头
            quasi_index_list: 准标识符属性index
            category_flag_list: 种类类型flag
    """
    trees = list()
    names = [attribute_names[x] for x in quasi_index_list]  # 提取准标识符属性名称
    for i in range(len(quasi_index_list)):
        if category_flag_list[i]:   # 种类类型的数据

            tree = {}
            data_path = os.path.join(path, dataset + '_hierarchy_' + names[i] + ".csv")
            file = open(data_path)
            tree['*'] = GTree('*')
            for line in file.readlines():
                line = line.strip()  # 去掉换行符
                tmp_list = line.split(';')  # 分割字符串
                tmp_list.reverse()
                last_index = len(tmp_list) - 1
                # 构建树
                for j, tmp in enumerate(tmp_list):
                    try:
                        tree[tmp]
                    except KeyError:
                        tree[tmp] = GTree(tmp, tree[tmp_list[j - 1]], (j == last_index))
            trees.append(tree)
        else:    # 数值类型的数据读取
            data_path = os.path.join(statistic_path, dataset + '_' + names[i] + '_static.pickle')
            numeric_dict, sort_value = pickle.load(open(data_path, 'rb'))
            trees.append(NRange(sort_value, numeric_dict))
    return trees

def read_pickle(path, dataset, att_name):
    """
    读取pickle文件中的统计数据
        参数说明: 
            path: 数据存储路径(results/numeric)
            dataset: 数据集名称
            name: 要读取的数据属性的名称
    """

    return result


def write_results(results, header, anon_method, result_path, num=''):
    # 写入结果
    with open(result_path, 'w', newline='') as file: 
        writer = csv.writer(file, delimiter=',')
        writer.writerow(header)
        writer.writerows(results)